const EventEmitter = require('events');
const EVENT = require('./IpcEvent');
export const FILE_FILTERS = {
    "EXCEL":{name:"Excel文件",extensions:["xlsx"]},
    "ALL":{name:"所有文件",extensions:["*"]}
}

class IpcClient extends EventEmitter{
    constructor(ipcRender){
        super();
        console.log("Ipc call create")
        this.ipc = ipcRender
        this.setMaxListeners(100);

    }
    _buildEvent(event,arg,cb){
        let ipcClinet = this;
        this.ipc.send(event,arg);
        this.once(event,cb);
        this.ipc.once(event, (e,a)=>{console.log(a); ipcClinet.emit(event,a);})
    }

    openFolder(arg,cb){
        console.log("选择目录！")
        this._buildEvent(EVENT.OPEN_FOLDER,arg,cb);
    }
    loadConfig(arg,cb){
        this._buildEvent(EVENT.LOAD_APPCONFIG,arg,cb);
    }
    saveConfig(arg,cb){
        this._buildEvent(EVENT.SAVE_APPCONFIG,arg,cb);
    }
    openWeb(project,isList){
        if(isList == 0  && project.currentVersion != null){
            let url = "/storage/" + project.currentVersion.webPath + "/";
            this.ipc.send(EVENT.COMMON_OPENURL,url);
        }else{
            let url = "/project/" + project.projectId + "/";
            this.ipc.send(EVENT.COMMON_OPENURL,url);
        }

    }
    findAllProjects(cb){
        console.log("加载所有项目！")
        let ipcClinet = this;
        this.ipc.send(EVENT.LIST_PROJECTS,{});
        this.once(EVENT.LIST_PROJECTS,cb);
        this.ipc.once(EVENT.LIST_PROJECTS, (e,a)=>{console.log(a); ipcClinet.emit(EVENT.LIST_PROJECTS,a);})
    }
    findProjectById(projectId,cb){
        const ipcClinet = this;
        const event = EVENT.VIEW_PROJECT;
        this.ipc.send(event,projectId);
        this.once(event,cb);
        this.ipc.once(event, (e,a)=>{console.log(a); ipcClinet.emit(event,a);});
    }
    async addNewVersion(version,cb){
        console.log("上传新版本！",version);
        let ipcClinet = this;
        const event = EVENT.ADD_VERSION;
        this.ipc.send(event,version);
        //注册回调接口，用于给前端发送消息
        this.once(event,cb);
        //注册IPCClient的回调接口，用于接收IPCAdapter并通过ipcClient触发的方式转发给前端
        this.ipc.once(event, (e,a)=>{console.log("Event callback:",event,"param:",a); ipcClinet.emit(event,a);});
        this.ipc.on(EVENT.ADD_VERSION_PROCESS,(e,a)=>{console.log(a); 
            cb(a);
            //ipcClinet.emit(EVENT.ADD_VERSION_PROCESS,a);
        });
    }
    addNewProject(project,cb){
        console.log("创建新项目",project);
        let ipcClinet = this;
        const event = EVENT.ADD_PROJECT;
        this.ipc.send(event,project);
        this.once(event,cb);
        this.ipc.once(event, (e,a)=>{console.log(a); ipcClinet.emit(event,a);});
    }
}

export const ipcClient = new IpcClient(window.ipcRenderer);